import numpy as np
import os
import glob
import imageio.v2 as iio   # pip install imageio


os.chdir(os.path.dirname(__file__))

def get_raw(path,Width,Height) :
    return np.fromfile(path,dtype='uint16').reshape(Height,Width,1)

# ========= 用户参数 =========
folder = r'./image'  # 原始 RAW 所在文件夹
offset_image ='avg_3072x3072_16u.raw'
prefix = '*.raw'           # 文件通配符
width  = 3072
height = 3072
# ============================
out_dir = 'corrected'
os.makedirs(out_dir, exist_ok=True)

files = sorted(glob.glob(os.path.join(folder, prefix)))
if not files:
    raise RuntimeError('目录下找不到匹配文件！')

# 用 64-bit 累加器防止溢出
acc = np.zeros((height, width), dtype=np.float64)
offset=get_raw(offset_image,width,height)
offset =offset.astype(np.float64)




print(f'共 {len(files)} 张图，开始累加…')
for idx, f in enumerate(files, 1):
    # 16-bit unsigned, big-endian (ImageJ 默认导出方式)
    img = np.fromfile(f, dtype='uint16').reshape(height, width,1).astype(np.float64)
    dst= img +100- offset
    dst = np.clip(dst, 0, 65535).astype(np.uint16)
    # 生成输出文件名
    out_name = f"{idx:04d}_16u.raw"
    dst.tofile(os.path.join(out_dir, out_name))
    print("第",idx,"张图像处理完成")